package com.test.android;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AndroidWSTestActivity extends Activity {
    /** Called when the activity is first created. */
    
    private static final String NAMESPACE = "http://www.webservicex.net/";
	private static final String URL = 
		"http://www.webservicex.net/geoipservice.asmx";	
	private static final String SOAP_ACTION = "http://www.webservicex.net/GetGeoIP";
	private static final String METHOD_NAME = "GetGeoIP";
	
	private TextView txtBuscar;
	private TextView txtPais;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        txtBuscar = (TextView) findViewById(R.id.txtBuscar);
        txtPais = (TextView) findViewById(R.id.txtPais);
        Button btnBuscar = (Button) findViewById(R.id.btnBuscar);
        
        btnBuscar.setOnClickListener(new OnClickListener(){
        	public void onClick(View v){
        		try{
        			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
        			request.addProperty("IPAddress", txtBuscar.getText().toString());
        			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        			envelope.dotNet = true;
        			envelope.bodyOut = request;
        			
        			HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        			androidHttpTransport.call(SOAP_ACTION, envelope);
        			//txtPais.setText(envelope.getResponse().toString());
        			SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
                    int elementCount = resultsRequestSOAP.getPropertyCount();

                    if(elementCount>0){
                        SoapObject element;
                        for(int i = 0;i<elementCount;i++){
                            element = (SoapObject)resultsRequestSOAP.getProperty(i);
                            txtPais.setText(element.getProperty("CountryName").toString());
                        }
                    }else{
                    	txtPais.setText("IP sin informacion");
                    }
        		} catch (Exception e) {
        			txtPais.setText("IP sin informacion");
                } 
        	}
        });
        
    }
}